<?php
/* ******************************
 *	Document Correction aJax actions
 * ******************************
 */
 
include('../../includes/classes/core.php');
include('../../includes/classes/logger.class.php');

$action	= $_REQUEST['act'];
$error	= '';
$data	= '';

$_log   = Logger::instance('../../log/operations/transfer/', Logger::OFF);

switch ($action) {
    case 'get_add_page':
		$page		= GetPage();
		$data		= array('page'	=> $page);
		
        break;
    case 'get_edit_page':
    	$id         = $_REQUEST['id'];
    	

    	
    	$page		= GetPage(GetDocumentData($id));
    	$data		= array('page'	=> $page);
    	
    	break;
    case 'get_local_id':
    	$data = array('local_id' => GetLocalID() );
    	
    	break;
    case 'get_list':
	    $count = $_REQUEST['count'];
	    $hidden = $_REQUEST['hidden'];
	    $doc_numb = $_REQUEST['doc_numb'];

	    $rResult = mysql_query("SELECT overhead_correction.id,
					    		overhead_correction.`date`,
								persons.`name`,
								overhead.waybill_number
								FROM overhead_correction
								LEFT JOIN overhead ON overhead.id = overhead_correction.overhead_id
								LEFT JOIN users ON users.id = overhead_correction.user_id
								LEFT JOIN persons ON persons.id = users.person_id
	    						");
		
		$data = array(
			"aaData"	=> array()
		);
		
		if(!$rResult){
			$error = 'Invalid query: ' . mysql_error();
		}else{
			while ( $aRow = mysql_fetch_array( $rResult ) )
			{
				$row = array();
				for ( $i = 0 ; $i < $count ; $i++ )
				{
					/* General output */
					$row[] = $aRow[$i];
				}
				$data['aaData'][] = $row;
			}
			
			$_log->logInfo('get_list');
		}
		
        break;

    case 'correction_done' :
    		$overhead_detail_id = $_REQUEST['id'];
    		$real_quantity      = $_REQUEST['quantity'];
    		$real_cost          = $_REQUEST['cost'];
    		$c_id               = $_REQUEST['c_id'];
    		$str                = substr($overhead_detail_id, 0, 1);

    		
    		CorrectionDone($overhead_detail_id, $real_quantity, $real_cost);
    		
    		if($str == 'O'){
    			$g_id = substr($overhead_detail_id, 1); 
    			UpdateDocDetail($g_id, $real_quantity, $real_cost);
    		}else{
    			UpdateDocDetail($overhead_detail_id, $real_quantity, $real_cost);
    		}
    		
    		
		break;
    case 'insert-details':
    	$l_id = $_REQUEST[l_id];
    	$doc  = $_REQUEST[doc_numb];
    	$check = GetDocType($doc);

    	if($check){
    		InsertDocDetails($doc, $l_id);
    	}else{
    		InsertDocDetailsB($doc, $l_id);
    	}
    	break;
    case 'save_correction' :
    	
    	$id = $_REQUEST['id'];
    	
    	InsertCorrection($id);
    	
    	
    	break;
    case 'clear_db':
		ClearDB();
		
        break;  
    default:
       $error = 'Action is Null';
}

$data['error'] = $error;

echo json_encode($data);


/* ******************************
 *	Document Correction Functions
 * ******************************
 */

function InsertCorrection($id){
	$user_id  = $_COOKIE['USERID'];
	$date 	 = date('Y-m-d H:i:s');
	
	$res = mysql_fetch_assoc(mysql_query("SELECT overhead_id AS `id`
										FROM overhead_detail
										WHERE id = (SELECT overhead_detail_id FROM overhead_correction_detail WHERE overhead_correction_id = $id LIMIT 1)"));
	
	mysql_query("INSERT INTO overhead_correction
				(`id`, `user_id`, `date`, `overhead_id`)
				VALUES($id,$user_id,'$date',$res[id])");
}

function InsertDocDetails($doc, $l_id){
	$user_id = $_COOKIE['USERID'];
	$date 	 = date('Y-m-d H:i:s');
	
	$res = mysql_query("SELECT DISTINCT 	`OD`.`id` AS `id`,
											`PI`.`production_id` AS `prod_id`,
											`OI`.`quantity` AS `qnt`,
											`OI`.`price` AS `price`
									FROM `overhead_detail` AS `OD` 
											LEFT JOIN `overhead` ON overhead.id = `OD`.overhead_id
											LEFT JOIN `production_identity` AS `PI` ON `OD`.`name` = `PI`.`rs_name` 
											LEFT JOIN `overhead_identity` AS `OI` ON `OD`.`overhead_id` = `OI`.`overhead_id` && `PI`.`id` = `OI`.`identity_id` && `OD`.`id` = `OI`.`overhead_detail_id`										
								WHERE overhead.waybill_number = '$doc' AND  overhead.waybill_number != ''");
	
	while ($row = mysql_fetch_assoc($res)){
		mysql_query("INSERT INTO overhead_correction_detail
					(user_id, overhead_correction_id, overhead_detail_id, date, production_id, old_quantity, old_cost)
					VALUES ($user_id, $l_id, $row[id],'$date', $row[prod_id], $row[qnt], $row[price])");
	}
}


function UpdateDocDetail($id, $quantity, $cost){
	mysql_query("UPDATE overhead_correction_detail
	SET
	new_quantity = $quantity,
	new_cost = $cost
	WHERE overhead_detail_id = $id");
}

function InsertDocDetailsB($doc, $l_id){
	$user_id = $_COOKIE['USERID'];
	$date 	 = date('Y-m-d H:i:s');

	$res = mysql_query("SELECT DISTINCT  	`OD`.`id`  AS `id`,
											`OD`.`goods_id` AS `prod_id`,
											`OD`.`quantity` AS `qnt`,
											`OD`.`price` AS `price`
											FROM 		`overhead_detail` AS `OD`
											LEFT JOIN 	`overhead` AS `O` ON `OD`.`overhead_id` = `O`.id
											WHERE 		`O`.`waybill_number` = '$doc'");

	while ($row = mysql_fetch_assoc($res)){
		mysql_query("INSERT INTO overhead_correction_detail
		(user_id, overhead_correction_id, overhead_detail_id, date, production_id, old_quantity, old_cost)
		VALUES ($user_id, $l_id, $row[id],'$date', $row[prod_id], $row[qnt], $row[price])");
	}
}

		
		
		
function GetDocType($doc_numb){
	$check = false;
	$res = mysql_fetch_assoc(mysql_query("SELECT overhead.stream AS `stream`
			FROM overhead
			WHERE overhead.waybill_number = '$doc_numb'"));

	if($res[stream] == 1){
		$check = true;
	}

	return $check;
}

function GetLocalID()
{
	GLOBAL $db;
	$id = $db->increment('overhead_correction');
	return $id;
}

function CorrectionDone($overhead_detail_id, $real_quantity, $real_cost){

	
						$res = mysql_fetch_assoc(mysql_query("SELECT		self_cost_history.id,
																			self_cost_history.date,
																			self_cost_history.production_id,
																			self_cost_history.current_quantity,
																			self_cost_history.current_cost,
																			self_cost_history.income_quantity,
																			self_cost_history.income_cost
																FROM    	self_cost_history
																WHERE   	self_cost_history.overhead_detail_id = $overhead_detail_id"));
						
						$id					= $res[id];
						$production_id		= $res[production_id];
						$date				= $res[date];
						
						$current_quantity   = $res[current_quantity];
						$current_cost		= $res[current_cost];
						$income_quantity    = $res[income_quantity];
						
						$result_quantity	= $current_quantity + $real_quantity;
						$result_cost		= ($current_quantity * $current_cost + $real_quantity * $real_cost) / ($current_quantity + $real_quantity);
						
						$diff              	= $real_quantity - $income_quantity;
						
						mysql_query("UPDATE self_cost_history
									 SET	self_cost_history.income_quantity 	= $real_quantity,
											self_cost_history.income_cost 		= $real_cost,
											self_cost_history.result_quantity 	= $result_quantity,
											self_cost_history.result_cost 		= $result_cost
									WHERE   self_cost_history.id = $id");
						
						$res1 = mysql_query("SELECT		self_cost_history.id,
														self_cost_history.current_quantity,
														self_cost_history.current_cost,
														self_cost_history.income_quantity,
														self_cost_history.income_cost
											FROM    	self_cost_history
											WHERE   	self_cost_history.id > $id AND self_cost_history.production_id = $production_id
											ORDER BY 	self_cost_history.id ASC");
						
						while ($row = mysql_fetch_assoc($res1)) {
							
							$current_quantity 	= $row[current_quantity] + $diff;
							$current_cost		= $result_cost;
							
							$result_quantity	= $current_quantity + $row[income_quantity];
							$result_cost 		= ($current_quantity * $current_cost +  $row[income_quantity] * $row[income_cost]) / ($current_quantity + $row[income_quantity]);
							
							
							mysql_query("UPDATE self_cost_history
										 SET	self_cost_history.current_quantity 	= $current_quantity,
												self_cost_history.current_cost 		= $current_cost,
												self_cost_history.result_quantity 	= $result_quantity,
												self_cost_history.result_cost 		= $result_cost
										WHERE   self_cost_history.id 				= $row[id]");
							
							
						
						}
						
						$res2 = mysql_query("	SELECT 		sale_transaction.end_date,
															sale_transaction_detail.id AS `det_id`
												FROM   		sale_transaction
												JOIN    	sale_transaction_detail ON sale_transaction.id = sale_transaction_detail.transaction_id
												WHERE 		sale_transaction.end_date > '$date' AND sale_transaction_detail.production_id = $production_id
												ORDER BY 	sale_transaction.end_date ASC");
						
						$res3 = mysql_query("	SELECT 		`self1`.`date` AS `start`,
															(SELECT `self_cost_history`.`date` FROM  `self_cost_history` WHERE `self_cost_history`.`date` > `self1`.`date` AND `self_cost_history`.`production_id` = $production_id LIMIT 1) AS `end`,
															`self1`.`result_cost` AS `self_cost`
												FROM 		`self_cost_history` AS `self1`
												WHERE    	`self1`.`production_id` = 202
												ORDER BY 	`self1`.`date` ASC");
						
						while ($row2 = mysql_fetch_assoc($res2)) {
							while ($row3 = mysql_fetch_assoc($res3)) {
								if ($row2[end_date] > $row3[start] && $row2[end_date] < $row3[end]) {

									mysql_query("UPDATE `sale_transaction_detail`
												 SET     sale_transaction_detail.self_cost = $row3[self_cost]
												 WHERE   sale_transaction_detail.production_id = $production_id AND sale_transaction_detail.id >= $row2[det_id]");
								}
							}
						}
	
	
}

function ClearDB()
{
	$req = mysql_query("SELECT	`id`
						FROM	`overhead_correction_detail`
						WHERE	`overhead_correction_id` NOT IN (SELECT `id` FROM `overhead_correction`)");

	while( $res = mysql_fetch_assoc($req)){
		mysql_query("DELETE
					 FROM
						`overhead_correction_detail`
					 WHERE
						`id` = '$res[id]'");
	}
}




function GetObject($object_id)
{
	$data = '';
	$req = mysql_query("SELECT	`id`, `name`
						FROM	`object`
						WHERE	`object`.`type` != 1 && `object`.`type` != 5 && `object`.`type` != 7 && `object`.`actived` = 1 && `object`.`type` = 2"); // <<<<---------------------Type!!!
		
	while( $res = mysql_fetch_assoc($req)){			
		if($res['id'] == $object_id){
			$data .= '<option value="' . $res['id'] . '" selected="selected">' . $res['name'] . '</option>';
		} else {
			$data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
		}				
	}
	return $data;
}



function GetCorrection(){
	$res =mysql_fetch_assoc(mysql_query(""));
	
	
	return $res;
}


function GetDocumentData($id){
	$res = mysql_fetch_assoc(mysql_query("SELECT overhead.waybill_number AS `w_number`,
											overhead_correction.overhead_id AS `id`
											FROM `overhead_correction`
											LEFT JOIN overhead ON overhead.id = overhead_correction.overhead_id
											WHERE overhead_correction.id = $id"));
	
	return $res;
}

function GetPage($res = '')
{
	$data = '
	<!-- jQuery Dialog -->
    <div id="add-edit-prod-form" class="form-dialog" title="შემადგენლობა">
    	<!-- aJax -->
	</div>
	<div id="dialog-form">
	    <fieldset>
	    	<legend>ძირითადი ინფორმაცია</legend>
			<table border="0" width="100%">
				<tr>
					<td><label for="document_number" style="line-height:25px;">დოკუმენტის №</label></td>
					<td>
						<div class="seoy-row" id="document_number_seoy">
							<input type="text" id="document_number" class="idle seoy-address" onblur="this.className=\'idle seoy-address\'" onfocus="this.className=\'activeField seoy-address\'" value="'.$res[w_number].'" />
							<button id="document_number_btn" class="combobox">document_number</button>
						</div>
					<td>
				</tr>
			   <tr>	
			</tr>
			</table>
			<table>
			   <tr><div id="act_info"></div></tr>
			</table>
        </fieldset>

		<fieldset>
	    	<legend>კორექტირებამდე</legend>

		    <div class="inner-table">
			    <div id="dt_example" class="ex_highlight_row">
			        <div id="container" class="overhead_container">
			        	<div id="button_area">
			        		<button id="delete_button_prod">წაშლა</button>
			        	</div>
			            <div id="dynamic">
			                <table class="display" id="prod_list">
			                    <thead>
			                        <tr id="datatable_header">				                        
			                            <th>ID</th>
										<th style="width:30px">№</th>
			                            <th style="width:100%; font-size:10px;">დასახელება<br>ზედნადებით/შეძენის აქტით</th>
										<th style="width:100%">დასახელება<br>ჩვენთან</th>
			                            <th class="min">რაოდ.</th>
										<th class="min">ერთ.ფასი</th>
										<th class="min">საქონლის ფასი</th>
			                        </tr>
			                    </thead>
			                    <thead>
			                        <tr class="search_header">				                        
			                            <th class="colum_hidden">
			                            	<input type="text" name="search_id" value="ფილტრი" class="search_init" />
			                            </th>
			                            <th>
			                            	
			                            </th>
										<th>
			                            	<input type="text" name="search_prod" value="ფილტრი" class="search_init" />
			                            </th>
										<th>
			                            	<input type="text" name="search_prod" value="ფილტრი" class="search_init" />
			                            </th>
										<th>
			                            	<input type="text" name="search_prod" value="ფილტრი" class="search_init" />
			                            </th>
										<th>
			                            	<input type="text" name="search_prod" value="ფილტრი" class="search_init" />
			                            </th>
										<th>
			                            	<input type="text" name="search_prod" value="ფილტრი" class="search_init" />
			                            </th>

			                        </tr>
			                    </thead>
			                </table>
			            </div>
			        </div>
			    </div>
			</div>
		</fieldset>
			
		<fieldset>
	    	<legend>კორექტირების შემდეგ</legend>

		    <div class="inner-table">
			    <div id="dt_example" class="ex_highlight_row">
			        <div id="container" class="overhead_container">
			            <div id="dynamic">
			                <table class="display" id="before_act">
			                    <thead>
			                        <tr id="datatable_header">				                        
			                            <th>ID</th>
										<th style="width:30px">№</th>
			                            <th style="width:100%; font-size:10px;">დასახელება<br>ზედნადებით/შეძენის აქტით</th>
										<th style="width:100%">დასახელება<br>ჩვენთან</th>
			                            <th class="min">რაოდ.</th>
										<th class="min">ერთ.ფასი</th>
										<th class="min">საქონლის ფასი</th>
			                        </tr>
			                    </thead>
			                    <thead>
			                        <tr class="search_header">				                        
			                            <th class="colum_hidden">
			                            	<input type="text" name="search_id" value="ფილტრი" class="search_init" />
			                            </th>
			                            <th>
			                            	
			                            </th>
										<th>
			                            	<input type="text" name="search_prod" value="ფილტრი" class="search_init" />
			                            </th>
										<th>
			                            	<input type="text" name="search_prod" value="ფილტრი" class="search_init" />
			                            </th>
										<th>
			                            	<input type="text" name="search_prod" value="ფილტრი" class="search_init" />
			                            </th>
										<th>
			                            	<input type="text" name="search_prod" value="ფილტრი" class="search_init" />
			                            </th>
										<th>
			                            	<input type="text" name="search_prod" value="ფილტრი" class="search_init" />
			                            </th>

			                        </tr>
			                    </thead>
			                </table>
			            </div>
			        </div>
			    </div>
			</div>
		</fieldset>
			
		<fieldset>
	    	<legend>კორექტირებას დაქვემდებარებული</legend>
		    <div class="inner-table">
			    <div id="dt_example" class="ex_highlight_row">
			        <div id="container" class="overhead_container">
			            <div id="dynamic">
			                <table class="display" id="after_act">
			                    <thead>
			                        <tr id="datatable_header">				                        
			                            <th>ID</th>
										<th style="width:30px">№</th>
			                            <th style="width:100%; font-size:10px;">დასახელება<br>ზედნადებით/შეძენის აქტით</th>
										<th style="width:100%">დასახელება<br>ჩვენთან</th>
			                            <th class="min">რაოდ.</th>
										<th class="min">ერთ.ფასი</th>
										<th class="min">საქონლის ფასი</th>
			                        </tr>
			                    </thead>
			                    <thead>
			                        <tr class="search_header">				                        
			                            <th class="colum_hidden">
			                            	<input type="text" name="search_id" value="ფილტრი" class="search_init" />
			                            </th>
			                            <th>
			                            	
			                            </th>
										<th>
			                            	<input type="text" name="search_prod" value="ფილტრი" class="search_init" />
			                            </th>
										<th>
			                            	<input type="text" name="search_prod" value="ფილტრი" class="search_init" />
			                            </th>
										<th>
			                            	<input type="text" name="search_prod" value="ფილტრი" class="search_init" />
			                            </th>
										<th>
			                            	<input type="text" name="search_prod" value="ფილტრი" class="search_init" />
			                            </th>
										<th>
			                            	<input type="text" name="search_prod" value="ფილტრი" class="search_init" />
			                            </th>

			                        </tr>
			                    </thead>
			                </table>
			            </div>
			        </div>
			    </div>
			</div>
		</fieldset>
		<!-- ID -->
		<input type="hidden" id="det_id" value="'.$res[id].'" />
		<input type="hidden" id="local_det_id" />
    </div>    
    ';
    
	return $data;
}
?>